package com.fengq1.timeaxis.controller;

import cn.hutool.core.util.StrUtil;
import com.fengq1.timeaxis.core.Result;
import com.fengq1.timeaxis.entity.HistoryNode;
import com.fengq1.timeaxis.service.HistoryNodeService;
import com.fengq1.timeaxis.service.RedisUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;

@RestController
@RequestMapping("history/node")
public class HistoryNodeController {

    private static final String LABEL_KEY = "labels";

    @Resource
    RedisUtil redisUtil;

    @Resource
    HistoryNodeService historyNodeService;

    @PostMapping
    public Result save(@RequestBody HistoryNode historyNode) {
        historyNode.setCreateTime(new Date());
        StringBuilder builder = new StringBuilder();
        //存标签
        Arrays.asList(historyNode.getLabels().split(",")).forEach(label -> {
                    redisUtil.lSet(LABEL_KEY, label);
                    builder.append("<").append(label).append(">");
                }
        );
        historyNode.setLabels(builder.toString());
        historyNode.setDelFlag(0);
        historyNodeService.save(historyNode);
        return Result.OK();
    }

    @PutMapping
    public Result update(@RequestBody HistoryNode historyNode) {
        historyNode.setCreateTime(new Date());
        StringBuilder builder = new StringBuilder();
        //存标签
        Arrays.asList(historyNode.getLabels().split(",")).forEach(label -> {
                    redisUtil.lSet(LABEL_KEY, label);
                    builder.append("<").append(label).append(">");
                }
        );
        historyNode.setLabels(builder.toString());
        historyNodeService.updateById(historyNode);
        return Result.OK();
    }

    @DeleteMapping
    public Result delete(@RequestParam String historyNodeId) {
        HistoryNode historyNode = historyNodeService.getById(historyNodeId);
        historyNodeService.updateById(historyNode);
        return Result.OK();
    }
}
